# 功能说明
#   本脚本主要用于找到当前下跌比较厉害的股票，具体方法如下：
#   1.找到历史最高价 pm
#   2.找到当前最高价 pc
#   3.计算当前价格占比 percent = pc/pm
#   4.返回 (code, date, pm, pc, percent)
# 输出格式
#   code, date, max_price, high_price, percent
#   sz.301030  2024-11-01   40.00   23.55  58.88%
# 相关技术
#   print('.', end='', flush=True)，加flush立即直接输出，不用等待缓冲一起输出。

import os, sys
import pandas as pd
from datetime import datetime, timedelta

def process_stock(csv_path, target_date='2025-01-15'):
    df = pd.read_csv(stock_file)#, index_col=0)
    df = df[df.date > '2024-07-01']
    len1 = len(df)
    df = df[df.isST == 0]
    len2 = len(df)
#    print(f'len1: {len1}, len2: {len2}')
    stock_code = os.path.basename(csv_path).replace('.csv', '')
    max_price = df.high.max()
    min_price = df.low.min()
    row0 = df[df.high == max_price].iloc[0]              # 定位到最高价的所在行
    last_row = df.iloc[-1]
    last_date = str(last_row.date)
    #print('last date:', last_date)
    high_price_series = df[df.date == last_date].high  # 指定日期的最高价
    if len(high_price_series) > 0 and len1 == len2:
        high_price = high_price_series.iloc[0]
        percent = high_price/max_price
        return [stock_code, row0.date, max_price, min_price, high_price, percent]
    return [stock_code, last_date, 0, 0, 0, 0]

# 输入股票代码文件和数据路径
stockinfo_path = 'all_stock_codes.csv'
data_dir = 'daily_data'

# 加载并开始循环处理，数据内容如下所示
# code,tradeStatus,code_name
# sh.000001,1,上证综合指数
df_codes = pd.read_csv(stockinfo_path)
res = []
counter = 0
print('processing...(Note: a single dot represents 100 stocks.)')
for index, row in df_codes.iterrows():
    if counter % 100 == 0:
        print('.', end='', flush=True)
    try:
        # row有3列数据：sh.000001,1,上证综合指数
        stock_file = os.path.join(data_dir, f'{row.tolist()[0]}.csv')
        if os.path.exists(stock_file):
            counter += 1
            res.append(process_stock(stock_file))
    except:
        continue

df = pd.DataFrame(res, columns=['code', 'date', 'max_price', 'min_price', 'high_price', 'percent1'])
df['percent2'] = df.high_price / df.min_price
#print('\n  code        date      max_price  min_price   cur_price   percent1    percent2')
print('\n 股票编号     日期      最高价格   最低价格    当前价格     下跌占比    已涨占比')
for id, row in df.sort_values(by='code').iterrows():
    try:
        dr = row.tolist()
        is_stock = 'sz.00' in dr[0] or 'sh.60' in dr[0]        # 只考虑沪市和深市
        in_price = dr[4] < 20                                  # 当前最高价范围
        in_range = 0.5 < dr[5] and dr[5] < 0.6 and dr[6] < 1.4 # 占比在 0.5-0.6 之间
        is_st = dr[0] == 'True'
        if is_stock and in_price and in_range:
            print(f'{dr[0]:10}{dr[1]:12}{dr[2]:10.2f}{dr[3]:10.2f}{dr[4]:12.2f}{dr[5]:12.2%}{dr[6]:12.2%}')
    except:
        print('x')

df.to_csv(f'results/result_{datetime.now():%Y%m%d_%H%M%S}.csv')
#print(df.sort_values(by='percent').head(100))

